package com.example.group.network.express_plus_app.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;

import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.example.group.network.express_plus_app.R;
import com.example.group.network.express_plus_app.SearchActivity;
import com.example.group.network.express_plus_app.adapter.LinearAdapter;
import com.example.group.network.express_plus_app.bean.Order;
import com.example.group.network.express_plus_app.bean.OrderInfoGroup;
import com.example.group.network.express_plus_app.widget.SpacesItemDecoration;
import com.google.android.material.tabs.TabLayout;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class HomeFragment extends Fragment  implements OnAddressListener, TabLayout.OnTabSelectedListener, View.OnClickListener {

    private HomeViewModel homeViewModel;
    @BindView(R.id.tv_GPS_location)
    TextView tv_GPS_location;
    @BindView(R.id.rv_order_look)
    RecyclerView rv_order_look;
    @BindView(R.id.iv_search)
    ImageView iv_search;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipe_refresh;
    @BindView(R.id.tv_weather)
    TextView tv_weather;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public MyLocationListener mLocationListener = new MyLocationListener();

    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.ll_refresh_location)
    LinearLayout ll_refresh_location;
    String type_text="全部";
    boolean refresh_type=false;

    WeatherSearchQuery mquery;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        ButterKnife.bind(this,root);
        XUI.initTheme(getActivity());
        tabs.addOnTabSelectedListener(this);
        //final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<ArrayList<Order>>() {
            @Override
            public void onChanged(ArrayList<Order> orders) {
                //订单展示
                LinearLayoutManager manager=new LinearLayoutManager(getActivity());
                manager.setOrientation(RecyclerView.VERTICAL);
                rv_order_look.setLayoutManager(manager);
                LinearAdapter adapter=
                        new LinearAdapter(getActivity(), orders);
                adapter.setOnItemClickListener(adapter);
                rv_order_look.setAdapter(adapter);
                if (refresh_type==true){
                    swipe_refresh.setRefreshing(false);
                    Toast.makeText(getActivity(), "刷新成功！", Toast.LENGTH_SHORT).show();
                    refresh_type=false;
                }


            }
        });

        findMyLocationByGPS();
        rv_order_look.setItemAnimator(new DefaultItemAnimator()); //设置列表项增删动画
        rv_order_look.addItemDecoration(new SpacesItemDecoration(6)); //设置列表项分割线
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
        //下拉刷新
        swipe_refresh.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        Log.i("下拉刷新", "onRefresh called from SwipeRefreshLayout");

                        // This method performs the actual data-refresh operation.
                        // The method calls setRefreshing(false) when it's finished.
                        refresh_type=true;
                        homeViewModel.findOrderByExpressDetailAddressAndExpressType(tv_GPS_location.getText().toString(),type_text);
                    }
                }
        );
        ll_refresh_location.setOnClickListener(this);
        return root;
    }

    @Override
    public void onFindAddress(String address) {
        if (!address.equals("请打开GPS,点击刷新")){
            //检索参数为城市和天气类型，实况天气为WEATHER_TYPE_LIVE、天气预报为WEATHER_TYPE_FORECAST
            mquery = new WeatherSearchQuery(address, WeatherSearchQuery.WEATHER_TYPE_LIVE);
            WeatherSearch mweathersearch=new WeatherSearch(getActivity());
            mweathersearch.setOnWeatherSearchListener(new WeatherSearch.OnWeatherSearchListener() {
                @Override
                public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int i) {
                    if (i == 1000) {
                        if (weatherLiveResult != null&&weatherLiveResult.getLiveResult() != null) {
                            LocalWeatherLive weatherlive = weatherLiveResult.getLiveResult();
                            tv_weather.setText(weatherlive.getWeather()+" "+weatherlive.getTemperature()+"°C");

                        }else {
                            Toast.makeText(getActivity(), "天气调用失败", Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(getActivity(), "天气调用失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

                }
            });
            mweathersearch.setQuery(mquery);
            mweathersearch.searchWeatherAsyn(); //异步搜索
            homeViewModel.findOrderByExpressDetailAddressAndExpressType(address,"全部");
        }
        tv_GPS_location.setText(address);
    }

    @SuppressLint("CheckResult")
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int tabPosition = tabs.getSelectedTabPosition();
        CharSequence text = tabs.getTabAt(tabPosition).getText();
        type_text=String.valueOf(text);
        homeViewModel.findOrderByExpressDetailAddressAndExpressType(tv_GPS_location.getText().toString(),String.valueOf(text));
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    public void findMyLocationByGPS(){
        mLocationListener.setOnAddressListener(this);
        //初始化定位
        mLocationClient = new AMapLocationClient(getActivity());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //声明AMapLocationClientOption对象
        AMapLocationClientOption mLocationOption = null;
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
//设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//获取一次定位结果：
//该方法默认为false。
        mLocationOption.setOnceLocation(true);

//获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);

//关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.ll_refresh_location){
            findMyLocationByGPS();
        }
    }
}